package org.zero.concurrency.demo.example.synccontainer;

import lombok.extern.slf4j.Slf4j;

import java.util.Iterator;
import java.util.Vector;

/**
 * @program: concurrency-demo
 * @description: 模拟并发执行
 * @author: 01
 * @create: 2018-10-14 00:01
 **/
@Slf4j
public class VectorExample3 {

    private static void test1(Vector<Integer> v1) {
        // 在遍历的同时进行了删除的操作，会抛出java.util.ConcurrentModificationException并发修改异常
        for (Integer integer : v1) {
            if (integer.equals(5)) {
                v1.remove(integer);
            }
        }
    }

    private static void test2(Vector<Integer> v1) {
        // 在遍历的同时进行了删除的操作，会抛出java.util.ConcurrentModificationException并发修改异常
        Iterator<Integer> iterator = v1.iterator();
        while (iterator.hasNext()) {
            Integer integer = iterator.next();
            if (integer.equals(5)) {
                v1.remove(integer);
            }
        }
    }

    private static void test3(Vector<Integer> v1) {
        // 可以正常删除
        for (int i = 0; i < v1.size(); i++) {
            v1.removeIf((integer) -> integer.equals(5));
        }
    }

    private static void test4(Vector<Integer> v1) {
        int delIndex = 0;
        for (Integer integer : v1) {
            if (integer.equals(5)) {
                delIndex = v1.indexOf(integer);
            }
        }
        v1.remove(delIndex);
    }

    private static void test5(Vector<Integer> v1){
        v1.removeIf((i) -> i.equals(5));
    }

    public static void main(String[] args) {
        Vector<Integer> vector = new Vector<>();
        for (int i = 1; i <= 5; i++) {
            vector.add(i);
        }
//        test4(vector);
//        test2(vector);
        test5(vector);
    }
}
